/*
 * Main UI class for MyLatexEditor v1.0
 * Includes methods and variables for application user interface
 */

/*
 * myLatexEdiotr.java
 *
 * Created on 22.Mar.2009, 21:51:51
 */
package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.Common.CommonGuiListener;
import com.meraklisina.latexeditor.mdi.Common.Tools;
import com.meraklisina.latexeditor.mdi.DialogActions.ActionOpen;
import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import com.meraklisina.latexeditor.toolbarCustomize.CustomizeForm;
import com.meraklisina.latexeditor.wizard.DynamicToolbarWizard;
import com.sun.pdfview.PDFFile;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author kursattopcu
 */
public class BlueLatexEditor extends javax.swing.JFrame {
	
	public static BlueLatexEditor _BlueLatexEditorIns ;
	
    private static String currentFileName;
    private static String tempPdfFileName = "temp";
    private final static String tempStatic = "temp";
    private int tempCounter = 0;
    private PDFFile pdffile = null;
    private int LastPageDisplayed = 1;
    private int DocNumberOfPages = 0;

    /** Creates new form myLatexEdiotr */
    public BlueLatexEditor() {
        initComponents();
        try {
			CommonGuiListener.initListeners();
		} catch (Exception e) {
			e.printStackTrace();
		}
        createToolbarBtn.setVisible(false);
        java.lang.Thread autoSaveThread=new java.lang.Thread(new AutoSaveThread(this));
        autoSaveThread.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        toolbarContextMenu = new javax.swing.JPopupMenu();
        customizeMenuItem = new javax.swing.JMenuItem();
        customizeDialog = new JDialog(this);
        customizeDialog.setModal(true);
        customizeDialog.setSize(430,300);
        customizeDialog.setResizable(false);
        customizeDialog.setTitle("Customize Toolbars");
        toolbarPanel = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        newButton = new javax.swing.JButton();
        openButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        boldButton = new javax.swing.JButton();
        italicButton = new javax.swing.JButton();
        underlineButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        alignLeftButton = new javax.swing.JButton();
        alignCenterButton = new javax.swing.JButton();
        alignRightButton = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        cutButton = new javax.swing.JButton();
        copyButton = new javax.swing.JButton();
        pasteButton = new javax.swing.JButton();
        jSeparator6 = new javax.swing.JToolBar.Separator();
        commentOutBtn = new javax.swing.JButton();
        commentInBtn = new javax.swing.JButton();
        createToolbarBtn = new javax.swing.JButton();
        jSeparator7 = new javax.swing.JToolBar.Separator();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxCovertTo = new javax.swing.JComboBox();
        convertToPdfButton = new javax.swing.JButton();
        hiddenLabel = new javax.swing.JLabel();
        btnPreview = new javax.swing.JButton();
        prevButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        pagesTextField = new javax.swing.JTextField();
        jSplitPane1 = new ExtendedSplitPane();
        jSplitPane1.setDividerLocation(0.7);
        previewPanel1 = new com.meraklisina.latexeditor.PreviewPanel();
        jPanel1 = new javax.swing.JPanel();
        tab_Editors = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        outputTextArea = new javax.swing.JTextArea();
        outputLabel = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenuExitItem = new javax.swing.JMenu();
        fileMenuNewItem = new javax.swing.JMenuItem();
        fileMenuOpen = new javax.swing.JMenuItem();
        fileMenuSave = new javax.swing.JMenuItem();
        fileMenuSaveAs = new javax.swing.JMenuItem();
        fileMenuCloseItem = new javax.swing.JMenuItem();
        fileMenuExit = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        jSeparator5 = new javax.swing.JSeparator();
        jMenu2 = new javax.swing.JMenu();
        editMenuItemUndo = new javax.swing.JMenuItem();
        editMenuItemRedo = new javax.swing.JMenuItem();
        editMenuCopyItem = new javax.swing.JMenuItem();
        editMenuPasteItem = new javax.swing.JMenuItem();
        editMenuCutItem = new javax.swing.JMenuItem();
        FindReplaceMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        customize = new javax.swing.JMenuItem();
        create = new javax.swing.JMenuItem();

        toolbarContextMenu.setName("toolbarContextMenu"); // NOI18N

        customizeMenuItem.setLabel("Customize");
        customizeMenuItem.setName("customizeMenuItem"); // NOI18N
        customizeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                customizeMenuItemActionPerformed(evt);
            }
        });

        customizeDialog.setName("customizeDialog"); // NOI18N

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SWEBlue LaTeX Editor v1.0");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("mainFrame"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        toolbarPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        toolbarPanel.setAutoscrolls(true);
        toolbarPanel.setName("toolbarPanel"); // NOI18N
        toolbarPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                BlueLatexEditor.this.mouseClicked(evt);
            }
        });
        toolbarPanel.setLayout(new javax.swing.BoxLayout(toolbarPanel, javax.swing.BoxLayout.LINE_AXIS));

        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        newButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_white.png"))); // NOI18N
        newButton.setToolTipText("New");
        newButton.setFocusable(false);
        newButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newButton.setName("newButton"); // NOI18N
        newButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(newButton);

        openButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/folder_magnify.png"))); // NOI18N
        openButton.setToolTipText("Open File...");
        openButton.setFocusable(false);
        openButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        openButton.setName("openButton"); // NOI18N
        openButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        openButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(openButton);

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/disk.png"))); // NOI18N
        saveButton.setToolTipText("Save");
        saveButton.setFocusable(false);
        saveButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveButton.setName("saveButton"); // NOI18N
        saveButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(saveButton);

        jSeparator3.setName("jSeparator3"); // NOI18N
        jToolBar1.add(jSeparator3);

        boldButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_bold.png"))); // NOI18N
        boldButton.setToolTipText("Bold");
        boldButton.setFocusable(false);
        boldButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        boldButton.setName("boldButton"); // NOI18N
        boldButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        boldButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boldButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(boldButton);

        italicButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_italic.png"))); // NOI18N
        italicButton.setToolTipText("Italic");
        italicButton.setFocusable(false);
        italicButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        italicButton.setName("italicButton"); // NOI18N
        italicButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        italicButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                italicButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(italicButton);

        underlineButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_underline.png"))); // NOI18N
        underlineButton.setToolTipText("Underline");
        underlineButton.setFocusable(false);
        underlineButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        underlineButton.setName("underlineButton"); // NOI18N
        underlineButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        underlineButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                underlineButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(underlineButton);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jToolBar1.add(jSeparator1);

        alignLeftButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_align_left.png"))); // NOI18N
        alignLeftButton.setToolTipText("Align Left");
        alignLeftButton.setFocusable(false);
        alignLeftButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        alignLeftButton.setName("alignLeftButton"); // NOI18N
        alignLeftButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        alignLeftButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alignLeftButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(alignLeftButton);

        alignCenterButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_align_center.png"))); // NOI18N
        alignCenterButton.setToolTipText("Align Center");
        alignCenterButton.setFocusable(false);
        alignCenterButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        alignCenterButton.setName("alignCenterButton"); // NOI18N
        alignCenterButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        alignCenterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alignCenterButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(alignCenterButton);

        alignRightButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/text_align_right.png"))); // NOI18N
        alignRightButton.setToolTipText("Align Right");
        alignRightButton.setFocusable(false);
        alignRightButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        alignRightButton.setName("alignRightButton"); // NOI18N
        alignRightButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        alignRightButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alignRightButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(alignRightButton);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jToolBar1.add(jSeparator2);

        cutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/cut.png"))); // NOI18N
        cutButton.setToolTipText("Cut");
        cutButton.setFocusable(false);
        cutButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cutButton.setName("cutButton"); // NOI18N
        cutButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        cutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cutButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(cutButton);

        copyButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/application_double.png"))); // NOI18N
        copyButton.setToolTipText("Copy");
        copyButton.setFocusable(false);
        copyButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        copyButton.setName("copyButton"); // NOI18N
        copyButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        copyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(copyButton);

        pasteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_paste.png"))); // NOI18N
        pasteButton.setToolTipText("Paste");
        pasteButton.setFocusable(false);
        pasteButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        pasteButton.setName("pasteButton"); // NOI18N
        pasteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        pasteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pasteButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(pasteButton);

        jSeparator6.setName("jSeparator6"); // NOI18N
        jToolBar1.add(jSeparator6);

        commentOutBtn.setText("Comment Out");
        commentOutBtn.setFocusable(false);
        commentOutBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        commentOutBtn.setName("commentOutBtn"); // NOI18N
        commentOutBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        commentOutBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commentOutBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(commentOutBtn);

        commentInBtn.setText("Comment In");
        commentInBtn.setFocusable(false);
        commentInBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        commentInBtn.setName("commentInBtn"); // NOI18N
        commentInBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        commentInBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commentInBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(commentInBtn);

        createToolbarBtn.setText("Create Toolbar");
        createToolbarBtn.setFocusable(false);
        createToolbarBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        createToolbarBtn.setName("createToolbarBtn"); // NOI18N
        createToolbarBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        createToolbarBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createToolbarBtnActionPerformed(evt);
            }
        });
        jToolBar1.add(createToolbarBtn);

        jSeparator7.setName("jSeparator7"); // NOI18N
        jToolBar1.add(jSeparator7);

        jLabel1.setText("Convert To ");
        jLabel1.setName("jLabel1"); // NOI18N
        jToolBar1.add(jLabel1);

        jComboBoxCovertTo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PDF", "DVI", "PS" }));
        jComboBoxCovertTo.setName("jComboBoxCovertTo"); // NOI18N
        jToolBar1.add(jComboBoxCovertTo);

        convertToPdfButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/building.png"))); // NOI18N
        convertToPdfButton.setToolTipText("Convert To...");
        convertToPdfButton.setFocusable(false);
        convertToPdfButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        convertToPdfButton.setName("convertToPdfButton"); // NOI18N
        convertToPdfButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        convertToPdfButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                convertToPdfButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(convertToPdfButton);

        hiddenLabel.setName("hiddenLabel"); // NOI18N

        btnPreview.setText("Preview");
        btnPreview.setName("btnPreview"); // NOI18N
        btnPreview.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPreviewActionPerformed(evt);
            }
        });

        prevButton.setText("<<");
        prevButton.setEnabled(false);
        prevButton.setName("prevButton"); // NOI18N
        prevButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                prevButtonActionPerformed(evt);
            }
        });

        nextButton.setText(">>");
        nextButton.setEnabled(false);
        nextButton.setName("nextButton"); // NOI18N
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        pagesTextField.setEditable(false);
        pagesTextField.setName("pagesTextField"); // NOI18N

        jSplitPane1.setDividerLocation(350);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        previewPanel1.setName("previewPanel1"); // NOI18N
        jSplitPane1.setRightComponent(previewPanel1);

        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setLayout(new java.awt.BorderLayout());

        tab_Editors.setName("tab_Editors"); // NOI18N
        jPanel1.add(tab_Editors, java.awt.BorderLayout.CENTER);

        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        outputTextArea.setColumns(20);
        outputTextArea.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        outputTextArea.setRows(5);
        outputTextArea.setDisabledTextColor(new java.awt.Color(255, 51, 51));
        outputTextArea.setEnabled(false);
        outputTextArea.setName("outputTextArea"); // NOI18N
        jScrollPane1.setViewportView(outputTextArea);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        outputLabel.setText("Output");
        outputLabel.setName("outputLabel"); // NOI18N
        jPanel2.add(outputLabel, java.awt.BorderLayout.PAGE_START);

        jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setLeftComponent(jPanel1);

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        fileMenuExitItem.setText("File");
        fileMenuExitItem.setName("fileMenuExitItem"); // NOI18N

        fileMenuNewItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuNewItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_white.png"))); // NOI18N
        fileMenuNewItem.setText("New");
        fileMenuNewItem.setToolTipText("Create New File");
        fileMenuNewItem.setName("fileMenuNewItem"); // NOI18N
        fileMenuNewItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuNewItemActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuNewItem);

        fileMenuOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuOpen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/folder_magnify.png"))); // NOI18N
        fileMenuOpen.setText("Open");
        fileMenuOpen.setToolTipText("Open Existing File");
        fileMenuOpen.setName("fileMenuOpen"); // NOI18N
        fileMenuOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuOpenActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuOpen);

        fileMenuSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/disk.png"))); // NOI18N
        fileMenuSave.setText("Save");
        fileMenuSave.setName("fileMenuSave"); // NOI18N
        fileMenuSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuSaveActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuSave);

        fileMenuSaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        fileMenuSaveAs.setText("Save As");
        fileMenuSaveAs.setName("fileMenuSaveAs"); // NOI18N
        fileMenuSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuSaveAsActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuSaveAs);

        fileMenuCloseItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        fileMenuCloseItem.setText("Close");
        fileMenuCloseItem.setName("fileMenuCloseItem"); // NOI18N
        fileMenuExitItem.add(fileMenuCloseItem);

        fileMenuExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        fileMenuExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/door_out.png"))); // NOI18N
        fileMenuExit.setText("Exit");
        fileMenuExit.setToolTipText("Exit");
        fileMenuExit.setName("fileMenuExit"); // NOI18N
        fileMenuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuExitActionPerformed(evt);
            }
        });
        fileMenuExitItem.add(fileMenuExit);

        jSeparator4.setName("jSeparator4"); // NOI18N
        fileMenuExitItem.add(jSeparator4);

        jSeparator5.setName("jSeparator5"); // NOI18N
        fileMenuExitItem.add(jSeparator5);

        jMenuBar1.add(fileMenuExitItem);

        jMenu2.setText("Edit");
        jMenu2.setName("jMenu2"); // NOI18N

        editMenuItemUndo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK));
        editMenuItemUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/arrow_undo.png"))); // NOI18N
        editMenuItemUndo.setText("Undo");
        editMenuItemUndo.setToolTipText("Undo");
        editMenuItemUndo.setName("jMenuItemUndo"); // NOI18N
        jMenu2.add(editMenuItemUndo);

        editMenuItemRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK));
        editMenuItemRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/arrow_redo.png"))); // NOI18N
        editMenuItemRedo.setText("Redo");
        editMenuItemRedo.setName("editMenuItemRedo"); // NOI18N
        jMenu2.add(editMenuItemRedo);

        editMenuCopyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        editMenuCopyItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/application_double.png"))); // NOI18N
        editMenuCopyItem.setText("Copy");
        editMenuCopyItem.setToolTipText("Copy Selection");
        editMenuCopyItem.setName("editMenuCopyItem"); // NOI18N
        editMenuCopyItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuCopyItemActionPerformed(evt);
            }
        });
        jMenu2.add(editMenuCopyItem);

        editMenuPasteItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        editMenuPasteItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/page_paste.png"))); // NOI18N
        editMenuPasteItem.setText("Paste");
        editMenuPasteItem.setToolTipText("Paste");
        editMenuPasteItem.setName("editMenuPasteItem"); // NOI18N
        editMenuPasteItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuPasteItemActionPerformed(evt);
            }
        });
        jMenu2.add(editMenuPasteItem);

        editMenuCutItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        editMenuCutItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/meraklisina/latexeditor/resources/icons/cut.png"))); // NOI18N
        editMenuCutItem.setText("Cut");
        editMenuCutItem.setToolTipText("Cut Selection");
        editMenuCutItem.setName("editMenuCutItem"); // NOI18N
        editMenuCutItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuCutItemActionPerformed(evt);
            }
        });
        jMenu2.add(editMenuCutItem);

        FindReplaceMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK));
        FindReplaceMenuItem.setText("Find/Replace");
        FindReplaceMenuItem.setName("FindReplaceMenuItem"); // NOI18N
        FindReplaceMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FindReplaceMenuItemActionPerformed(evt);
            }
        });
        jMenu2.add(FindReplaceMenuItem);

        jMenuBar1.add(jMenu2);

        jMenu1.setText("Toolbar");
        jMenu1.setName("jMenu1"); // NOI18N

        customize.setText("Customize");
        customize.setName("customize"); // NOI18N
        customize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                customizeMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(customize);

        create.setText("Create");
        create.setName("create"); // NOI18N
        create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createToolbarBtnActionPerformed(evt);
            }
        });
        jMenu1.add(create);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(toolbarPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
                            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE))
                        .addComponent(hiddenLabel)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPreview)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(prevButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(pagesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nextButton))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(toolbarPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPreview)
                    .addComponent(prevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pagesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(hiddenLabel)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 514, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void LoadToolbars() {
        String executionPath = System.getProperty("user.dir");
        executionPath = executionPath.replace("\\", "/") + "/AppConfig.xml";
        ToolBarHandler handler = ToolBarHandler.getHandler();
        handler.setContainer(toolbarPanel);
        //String url = getPathToJarfileDir(handler);
        try {
            //String temp = url + "/AppConfig.xml";
            handler.Generate(executionPath);//C:/Documents and Settings/kursattopcu/My Documents/NetBeansProjects/MyLatexEditor/src/mylatexeditor

            
            
            toolbarPanel.setVisible(true);
            outputTextArea.setText("Toolbars successfully installed...");
            toolbarPanel.revalidate();
        } catch (Exception ex) {
            outputTextArea.setText(ExceptionHandler.ProcessException(ex) + " PATH: " + executionPath);
        }
    }

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        String executionPath = System.getProperty("user.dir");
        executionPath = executionPath.replace("\\", "/");
    	Tools tool = new Tools(executionPath + "/"/*"/src/com/meraklisina/latexeditor/mdi/"*/, "");
        tool.InitializeTextEditors(this.tab_Editors);

        // add undo/redo to loaded text editors
        UndoRedo u = new UndoRedo();
        u.applyToTextEditors(this.tab_Editors, this.editMenuItemUndo, this.editMenuItemRedo);

        this.LoadToolbars();
        this.cf=new CustomizeForm(this.customizeDialog);
        this.customizeDialog.getContentPane().add(cf);
    }//GEN-LAST:event_formWindowOpened

    private void saveState() {
        TextEditors ClsTextEditor = new TextEditors();
        if (ClsTextEditor.WriteIntoXmlTextEditor()) {
            while (ClsTextEditor.getEditors().size() > 0) {
                ClsTextEditor.CloseTabAtDialog(this.tab_Editors, ClsTextEditor.GetLastChangedEditor(this.tab_Editors));
            }
        }
        ToolBarHandler.getHandler().serializeToolBars();
    }

    public void NewTab() {
        TextEditors ClsTextEditor = new TextEditors();
        ClsTextEditor.AddTab(tab_Editors);

        // apply undo/redo functionality to the new tab
        new UndoRedo(ClsTextEditor.GetJTextPane(tab_Editors), this.editMenuItemUndo, this.editMenuItemRedo);
    }

    public void OpenFile() {
        ActionOpen ClsActionOpen = new ActionOpen();
        ClsActionOpen.OpenDialog(tab_Editors);

         // apply undo/redo functionality to the new tab
         TextEditors ClsTextEditor = new TextEditors();
         new UndoRedo(ClsTextEditor.GetJTextPane(this.tab_Editors), this.editMenuItemUndo, this.editMenuItemRedo);
    }

    public void Save(boolean IsSaveAs) {
        TextEditors ClsTextEditor = new TextEditors();
        ClsTextEditor.SaveTab(this.tab_Editors, IsSaveAs);
    }


    /*
     * Bold Toolbar Button Action Handler Method
     * */
    private void boldButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boldButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\textbf{" + selected + "}";
        replaceSelectedText(editors, replacement);
}//GEN-LAST:event_boldButtonActionPerformed

    public static String getSelectedText(TextEditors editors){
        String selectedText = editors.GetText(tab_Editors);
        if(selectedText == null)
            selectedText = "";
        return selectedText;
    }

    public static void replaceSelectedText(TextEditors editors, String replacement){
        int tabIndex = tab_Editors.getSelectedIndex();
        editors.ReplaceSelectedText(tab_Editors, tabIndex, replacement);
    }
    /*
     * File->Open Menu Item Action Handler
     * */
    private void fileMenuOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuOpenActionPerformed
        //openButtonActionPerformed(evt);
        OpenFile();
    }//GEN-LAST:event_fileMenuOpenActionPerformed

    /*
     * New File Toolbar Button Action Handler
     * */
    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed

        NewTab();
    }//GEN-LAST:event_newButtonActionPerformed

    /*
     * Save Toolbar Button Action Handler
     * */
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        Save(false);
    }//GEN-LAST:event_saveButtonActionPerformed

    /*
     * File->New Menu Item Action Handler
     * */
    private void fileMenuNewItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuNewItemActionPerformed
        //newButtonActionPerformed(evt);
        NewTab();
}//GEN-LAST:event_fileMenuNewItemActionPerformed

    /*
     * File->Save Menu Item Action Handler
     * */
    private void fileMenuSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuSaveActionPerformed
        //fileMenuSaveActionPerformed(evt);
        Save(false);
    }//GEN-LAST:event_fileMenuSaveActionPerformed

    /*
     * File->SaveAs Action Handler
     * */
    private void fileMenuSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuSaveAsActionPerformed
        Save(true);
    }//GEN-LAST:event_fileMenuSaveAsActionPerformed

    /*
     * Italic Toolbar Button Action Handler
     * */
    private void italicButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_italicButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\textit{" + selected + "}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_italicButtonActionPerformed

    /*
     * Underline Toolbar Button Action Handler Method
     * */
    private void underlineButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_underlineButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\underline{" + selected + "}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_underlineButtonActionPerformed

    /*
     * Align Left Toolbar Button Action Handler Method
     * */
    private void alignLeftButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alignLeftButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\begin{flushleft}\n" + selected + "\n\\end{flushleft}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_alignLeftButtonActionPerformed

    /*
     * Align Center Toolbar Button Action Handler Method
     * */
    private void alignCenterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alignCenterButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\begin{center}\n" + selected + "\n\\end{center}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_alignCenterButtonActionPerformed

    /*
     * Align Right Toolbar Button Action Handler Method
     * */
    private void alignRightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alignRightButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "\\begin{flushright}\n" + selected + "\n\\end{flushright}";
        replaceSelectedText(editors, replacement);
    }//GEN-LAST:event_alignRightButtonActionPerformed

    /*
     * Cut Toolbar Button Action Handler Method
     * */
    private void cutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cutButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        String replacement = "";
        replaceSelectedText(editors, replacement);
        hiddenLabel.setVisible(false);
        hiddenLabel.setText(selected);
    }//GEN-LAST:event_cutButtonActionPerformed

    /*
     * Copy Toolbar Button Action Handler Method
     * */
    private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyButtonActionPerformed
        TextEditors editors = new TextEditors();
        String selected = getSelectedText(editors);
        hiddenLabel.setVisible(false);
        hiddenLabel.setText(selected);
    }//GEN-LAST:event_copyButtonActionPerformed

    /*
     * Paste Toolbar Button Action Handler Method
     * */
    private void pasteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pasteButtonActionPerformed
        TextEditors editors = new TextEditors();
        replaceSelectedText(editors, hiddenLabel.getText());
    }//GEN-LAST:event_pasteButtonActionPerformed

    /*
     * Edit->Copy Menu Item Action Handler Method
     * */
    private void editMenuCopyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuCopyItemActionPerformed
        copyButtonActionPerformed(evt);
    }//GEN-LAST:event_editMenuCopyItemActionPerformed

    /*
     * Edit->Paste Menu Item Action Handler Method
     * */
    private void editMenuPasteItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuPasteItemActionPerformed
        pasteButtonActionPerformed(evt);
    }//GEN-LAST:event_editMenuPasteItemActionPerformed

    /*
     * Open Button Action Handler Method
     * */
    private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed

        OpenFile();
    }//GEN-LAST:event_openButtonActionPerformed

    /*
     * Bold Toolbar Button Action Handler Method
     * */
    private void commentOutBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commentOutBtnActionPerformed
        TextEditors editors = new TextEditors();
        editors.CommentInOut(tab_Editors, true, "%");
}//GEN-LAST:event_commentOutBtnActionPerformed

    /*
     * File->Exit Menu Item Action Handler Method
     * */
    private void fileMenuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuExitActionPerformed
        System.exit(0);
}//GEN-LAST:event_fileMenuExitActionPerformed

    /*
     * Build Toolbar Button Action Handler Method
     * */
    private void convertToPdfButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_convertToPdfButtonActionPerformed

            // save the file first
         try{
            Save(false);
            outputTextArea.setText("\nThe file saved successfully: ");
         }catch(Exception er){
            outputTextArea.setText("\nThe file cannot be saved!\nOperation cancelled");
            return;
         }

        try{
            String selectedBuilder = (String)jComboBoxCovertTo.getSelectedItem();
            MixTexStuff mixtex = new MixTexStuff();
            if(selectedBuilder.equalsIgnoreCase("DVI")){
                mixtex.buildProcess("latex.exe", outputTextArea, tab_Editors);
            }else if(selectedBuilder.equalsIgnoreCase("PDF")){
                mixtex.buildProcess("pdflatex.exe", outputTextArea, tab_Editors);
            }else if(selectedBuilder.equalsIgnoreCase("PS")){
                mixtex.buildProcess("dvips.exe", outputTextArea, tab_Editors);
            }
        }catch(Exception ee){
            outputTextArea.setText("\nError! Operation cannot be completed.");
        }     
    }//GEN-LAST:event_convertToPdfButtonActionPerformed

    private void commentInBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commentInBtnActionPerformed
        TextEditors editors = new TextEditors();
        editors.CommentInOut(tab_Editors, false, "%");
    }//GEN-LAST:event_commentInBtnActionPerformed


    private void mouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mouseClicked
        if(evt.getButton()==MouseEvent.BUTTON3){
            mouseRightClicked(evt);
        }
}//GEN-LAST:event_mouseClicked
    private void mouseRightClicked(java.awt.event.MouseEvent evt) {
        // delete old ones
        this.toolbarContextMenu.removeAll();
        // add new toolbar menuitems
        ToolBarHandler handler=ToolBarHandler.getHandler();
        for(LatexToolBar tb:handler.getToolbars()){
            toolbarContextMenu.add(new LatexToolbarMenuItem(tb));
        }
        toolbarContextMenu.add(new JSeparator());
        toolbarContextMenu.add(this.customizeMenuItem);
        // display popupmenu
        this.toolbarContextMenu.show(this, evt.getXOnScreen(), evt.getYOnScreen());
    }
    private void editMenuCutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuCutItemActionPerformed
        cutButtonActionPerformed(evt);
    }//GEN-LAST:event_editMenuCutItemActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        saveState();
    }//GEN-LAST:event_formWindowClosing

    private void customizeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customizeMenuItemActionPerformed
        this.cf.reload();
        this.customizeDialog.setVisible(true);
    }//GEN-LAST:event_customizeMenuItemActionPerformed

    private void FindReplaceMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FindReplaceMenuItemActionPerformed
        // TODO add your handling code here:
        JDialog dialog=new JDialog();
        FindReplace findReplace=new FindReplace(dialog, this.tab_Editors);
        dialog.getContentPane().add(findReplace);

        dialog.setTitle("Find/Replace");
        dialog.setSize(400, 175);
        dialog.setLocation((int)this.getLocation().getX() + 200, (int)this.getLocation().getY() + 200);
        dialog.setResizable(false);
        dialog.setModal(true);
        dialog.setVisible(true);

    }//GEN-LAST:event_FindReplaceMenuItemActionPerformed

    /**
     * Generates the pdf of the currently selected tab document.
     * @return
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    private boolean generatePdf() throws FileNotFoundException, IOException {
        TextEditors ClsTextEditor = new TextEditors();
        int index = tab_Editors.getSelectedIndex();
        JTextPane textPane = ClsTextEditor.GetJTextPane(tab_Editors);
        String filePath = ClsTextEditor.GetRealPath(index);
        currentFileName = filePath;
        Process proc = null;
        ProcessBuilder pbuilder = new ProcessBuilder();
        pbuilder.directory(new File(getFilePath(currentFileName)));
        BufferedReader input;
        //boş tmp bi pdffile ver
        //changeDisplay();

        if (!new File(currentFileName).exists()) {
            return false;
        }
        try {
            String[] ex = {"pdflatex", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", getFilePath(currentFileName), currentFileName};
            pbuilder.command(ex);
            proc = pbuilder.start();
            String line;

            input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            while ((line = input.readLine()) != null) {
                outputTextArea.setText("[output] " + line + "\n");
            }
            input.close();

            input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            while ((line = input.readLine()) != null) {
                outputTextArea.setText("[errors] " + line + "\n");
            }
            input.close();

            int indexOfBSlash = currentFileName.lastIndexOf("\\");
            String pathDirectory = currentFileName.substring(0, indexOfBSlash);
            File oldTempFile = new File(pathDirectory + "\\" + tempPdfFileName);
            
            tempPdfFileName = tempStatic + Integer.toString(tempCounter);
            tempCounter++;

            copyToTempPdf(currentFileName, tempPdfFileName);
            if(oldTempFile.exists()){
                try{
                    oldTempFile.deleteOnExit();
                }
                catch(SecurityException sec){
                    String error = "sec exception";
                }
                catch(Exception exs){
                    String error = exs.getMessage();
                }
                
            }
            int value = proc.waitFor();
            if (value != 0) {
                return false;
            }
            return true;
        } catch (Throwable e) {
            outputTextArea.setText("\npdflatex: command not found " + e.getMessage()+ e.toString());
            return false;
        }
        finally {
            if (proc != null) {
                try {
                    proc.getInputStream().close();
                    proc.getOutputStream().close();
                    proc.getErrorStream().close();
                    proc.destroy();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * Copies the content of tex file to a new file
     * @param pathOriginal the path of the tex file
     * @param tempFileName name of the file destination file
     * @throws java.io.IOException
     */
    public void copyToTempPdf(String pathOriginal, String tempFileName) throws IOException{
        //changeDisplay();
        int indexOfBSlash = pathOriginal.lastIndexOf("\\");
        String pathDirectory = pathOriginal.substring(0, indexOfBSlash);
        String pathOriginalPdf = pdfExt(pathOriginal);
        String pathTemp = pathDirectory + "\\" + tempFileName;
        File fileOriginal = new File(pathOriginalPdf);
        File fileTemp = new File(pathTemp);

        try {
            InputStream in = new FileInputStream(fileOriginal);
            OutputStream out = new FileOutputStream(fileTemp);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0){
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getMessage());
        }
        fileTemp.deleteOnExit();
    }

    /**
     * Returns the pdf extension string of the tex file
     * @param texFilename name of the tex file
     * @return   string with pdf extension
     */
    private String pdfExt(String texFilename) {
        return texFilename.replaceFirst("[.][a-zA-Z]+$", ".pdf");
    }

    /**
     * Changes the preview to the given tex file's pdf
     * @param texFileName tex file name that will be screen pn preview panel. Not the absolute path. Just file name
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public void changeDisplay(String texFileName) throws FileNotFoundException, IOException{
        int indexOfBSlash = currentFileName.lastIndexOf("\\");
        String pathDirectory = currentFileName.substring(0, indexOfBSlash);
        File fileTex = new File(pathDirectory + "\\" + texFileName);
        //File file = new File(pdfExt("C:\\Documents and Settings\\vedat.ekiz\\Desktop\\yyyy\\tmp.tex"));
        File filePdf = new File(pdfExt(fileTex.getAbsolutePath()));
        try{
            OutputStream out = new FileOutputStream(fileTex);
            String def = "\\documentclass{article}\n\\begin{document}\nERROR\n\\end{document}";
            byte[] buff = def.getBytes();
            out.write(buff, 0, buff.length);
        }catch(Exception ex){

        }
        RandomAccessFile raf = new RandomAccessFile(filePdf, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        pdffile = new PDFFile(buf);
        previewPanel1.Update(pdffile, 1, true);
    }

    private String getFilePath(String fileName) {
         String newStr = "";
        try {
            //String[] Str = fileName.split(File.separator);
            String[] Str = fileName.split("\\" + File.separator);
            if (Str.length == 0) {
                return null;
            }

            for (int i = 0; i < Str.length - 1; i++) {
                newStr += Str[i] + File.separatorChar;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return newStr;
    }

    public int Notify(String fileName) {
        return Notify(true, fileName);
    }

    /**
     * 
     * @param if the page will be refreshed then true, otherwise false
     * @param fileName the file name to be previewed
     * @return the total number of pages
     */
    public int Notify(boolean hard, String fileName) {
        if (previewPanel1 != null) {
            try {
                ByteBuffer buf;
                if (hard) { // file needs to be refreshed
                    //File file = new File(pdfExt(this.currentFileName));
                    String filePath = this.currentFileName.substring(0, this.currentFileName.lastIndexOf("\\")) + "\\" + fileName;
                    File file = new File(pdfExt(filePath));
                    RandomAccessFile raf = new RandomAccessFile(file, "r");
                    FileChannel channel = raf.getChannel();
                    buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                    pdffile = new PDFFile(buf);
                    raf.close();
                    buf.clear();
                    channel.close();
                }
                previewPanel1.Update(pdffile, LastPageDisplayed, hard);
                final int retval = pdffile.getNumPages();

                if (hard) {
                    if (LastPageDisplayed != 1) {
                        prevButton.setEnabled(true);
                    }
                    if (LastPageDisplayed < retval) {
                        nextButton.setEnabled(true);
                    }
                    if (retval < LastPageDisplayed) {
                        LastPageDisplayed = retval;
                        nextButton.setEnabled(false);
                        previewPanel1.Update(pdffile, LastPageDisplayed, false);
                    }
                }
                final int page = LastPageDisplayed;
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        pagesTextField.setText(page + "/" + retval);
                    }
                });

                return retval;
            } catch (IOException ex) {
                Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return -1;
    }

    private void btnPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviewActionPerformed
        // TODO add your handling code here:
        Save(false);
        try {
            if (generatePdf()) {
                DocNumberOfPages = Notify(tempPdfFileName);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_btnPreviewActionPerformed

    private void prevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prevButtonActionPerformed
        // TODO add your handling code here:
        if (LastPageDisplayed > 1) {
            LastPageDisplayed--;
            Notify(false, tempPdfFileName);
            if (LastPageDisplayed == 1) {
                prevButton.setEnabled(false);
            }
            nextButton.setEnabled(true);
        }
    }//GEN-LAST:event_prevButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        // TODO add your handling code here:
        if (LastPageDisplayed < DocNumberOfPages) {
            LastPageDisplayed++;
            Notify(false, tempPdfFileName);
            prevButton.setEnabled(true);
            if (LastPageDisplayed == DocNumberOfPages) {
                nextButton.setEnabled(false);
            }
        }
    }//GEN-LAST:event_nextButtonActionPerformed

    private void createToolbarBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createToolbarBtnActionPerformed
        JDialog dia = new JDialog();
        DynamicToolbarWizard wizard = new DynamicToolbarWizard(dia);
        dia.getContentPane().add(wizard);

        dia.setTitle("Toolbar Wizard");
        dia.setSize(600, 450);
        //dialog.setLocation((int)mainPanel.getLocation().getX() + 200, (int)mainPanel.getLocation().getY() + 200);
        dia.setResizable(true);
        dia.setModal(true);
        dia.setVisible(true);

        while(wizard.hasFocus()){
            //wait until button created
        }

        if(wizard.getToolbar() != null){
            //int toolbarCount = ToolBarHandler.getHandler().getToolbars().size();
            ToolBarHandler.getHandler().getToolbars().add(wizard.getToolbar());
            ToolBarHandler.getHandler().serializeToolBars();
        }
    }//GEN-LAST:event_createToolbarBtnActionPerformed

    /*
     * Dyanmic LaTeX Toolbar Buttons Action Handler Method
     * THIS METHOD IS FOR v1.1
     * */
    public static void PerformLatexButtonAction(LatexButton btn) {
        try {
            TextEditors editors = new TextEditors();
            String expression = btn.getExpressionTemplate();
            if (getSelectedText(editors).isEmpty()) {
                replaceSelectedText(editors, expression);
            } else {
                String prefix = btn.getPrefix();
                String suffix = btn.getSuffix();
                String selected = getSelectedText(editors);
                if(prefix == null)
                    prefix = "";

                if(suffix == null)
                    suffix = "";
                
                replaceSelectedText(editors, prefix + selected + suffix);
            }
        } catch (Exception ex) {
            outputTextArea.setText("Error: " + ex.getMessage());
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {                	
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(BlueLatexEditor.class.getName()).log(Level.SEVERE, null, ex);
                }
                _BlueLatexEditorIns = new BlueLatexEditor();
                _BlueLatexEditorIns.setVisible(true);
            }
        });
    }
    public String commandResult;
    private CustomizeForm cf=null;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem FindReplaceMenuItem;
    private javax.swing.JButton alignCenterButton;
    private javax.swing.JButton alignLeftButton;
    private javax.swing.JButton alignRightButton;
    private javax.swing.JButton boldButton;
    private javax.swing.JButton btnPreview;
    private javax.swing.JButton commentInBtn;
    private javax.swing.JButton commentOutBtn;
    private javax.swing.JButton convertToPdfButton;
    private javax.swing.JButton copyButton;
    private javax.swing.JMenuItem create;
    private javax.swing.JButton createToolbarBtn;
    private javax.swing.JMenuItem customize;
    private javax.swing.JDialog customizeDialog;
    private javax.swing.JMenuItem customizeMenuItem;
    private javax.swing.JButton cutButton;
    private javax.swing.JMenuItem editMenuCopyItem;
    private javax.swing.JMenuItem editMenuCutItem;
    private javax.swing.JMenuItem editMenuItemRedo;
    private javax.swing.JMenuItem editMenuItemUndo;
    private javax.swing.JMenuItem editMenuPasteItem;
    private javax.swing.JMenuItem fileMenuCloseItem;
    private javax.swing.JMenuItem fileMenuExit;
    private javax.swing.JMenu fileMenuExitItem;
    private javax.swing.JMenuItem fileMenuNewItem;
    private javax.swing.JMenuItem fileMenuOpen;
    private javax.swing.JMenuItem fileMenuSave;
    private javax.swing.JMenuItem fileMenuSaveAs;
    private javax.swing.JLabel hiddenLabel;
    private javax.swing.JButton italicButton;
    private javax.swing.JComboBox jComboBoxCovertTo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JToolBar.Separator jSeparator6;
    private javax.swing.JToolBar.Separator jSeparator7;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton newButton;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton openButton;
    private javax.swing.JLabel outputLabel;
    private static javax.swing.JTextArea outputTextArea;
    private javax.swing.JTextField pagesTextField;
    private javax.swing.JButton pasteButton;
    private javax.swing.JButton prevButton;
    private com.meraklisina.latexeditor.PreviewPanel previewPanel1;
    private javax.swing.JButton saveButton;
    public static javax.swing.JTabbedPane tab_Editors;
    private javax.swing.JPopupMenu toolbarContextMenu;
    private javax.swing.JPanel toolbarPanel;
    private javax.swing.JButton underlineButton;
    // End of variables declaration//GEN-END:variables
}
